<template>
	<view class="u-wrap">
		<!-- #ifdef APP-PLUS -->
		<view class="status-bar" :style="{'height':statusbarH+'px'}"></view>
		<!-- #endif -->

		<view class="sort-search" @click="tosearch">
			<u-search bgColor="#F6F7FB" :showAction="false" placeholder="请输入搜索内容"></u-search>
		</view>
		<view class="u-menu-wrap cate" :style="{'height': appCateHeight}">
			<scroll-view scroll-y scroll-with-animation class="left-view" :scroll-top="scrollTop"
				:scroll-into-view="itemId">
				<view v-for="(item,index) in scrolllist" :key="index" class="left-view-item"
					:class="{'left-view-item-active':item.id==cat_id_1}" @tap.stop="scrolllistto(item.id)">
					<text class="u-line-1">{{item.name}}</text>
				</view>
			</scroll-view>
			<view class="right-view">
				<!-- <scroll-view scroll-x class="top-box">
					<view class="top-box-con">
						<view class="top-box-item" @tap.stop="swichMenu(item.id)" :class="{'act':cat_id_2 == item.id}"
							v-for="(item,index) in tabbar" :key="index">{{item.name}}</view>
					</view>
				</scroll-view> -->
				<scroll-view :scroll-top="scrollRightTop" :enable-flex = "true" scroll-y scroll-with-animation class="right-box"
					@scroll="rightScroll" @scrolltolower="scrolltolower">
					<block v-if="tabbarsun.length>0">
						<view class="goods-row-item" v-for="(item,index) in tabbarsun" :key="index"
							@tap='jump(`/pages/goods/goods-detail`,item.goods_id)'>
							<image :src="item.goods_img" mode="widthFix" class="goods-img"></image>
							<view class="right">
								<text class="goods-name">{{item.goods_name}}</text>
								<text class="bot_two_name" v-html="item.goods_remark" v-if="false"></text>
								<view class="right-bot">
									<view class="bot_bot_one">
										<text>￥</text>
										<text class="price">{{item.goods_price}}</text>
									</view>
									<text class="bot_bot_two" v-if="false">￥{{item.market_price}}</text>
									<text class="bot_bot_three">销量：{{item.sales_sum}}</text>
								</view>
							</view>
						</view>
					</block>
					<view class="empty-container" v-else>
						<u-empty text="暂无相关商品"
							icon="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/common/empty.png" />
					</view>
				</scroll-view>
			</view>
		</view>

		<u-popup :closeOnClickOverlay="false" :show="loginShow" @close="loginShow=false" mode="center"
			bgColor="transparent" :overlayOpacity="0.6">
			<view class="weixin-login">
				<view class="weixin-login-info">
					<text class="text">登录后可体验完整功能</text>
					<button :disabled="loginDisabled" type="primary" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber" class="weixin-login-btn">微信授权登录</button>
				</view>
				<view class="weixin-login-bot">
					<image src="https://farm-city.oss-cn-hangzhou.aliyuncs.com/static/images/alert-close.png"
						@click="loginShow=false" mode="widthFix" />
				</view>
			</view>
		</u-popup>
		<my-tabbar></my-tabbar>
	</view>
</template>
<script>
	// import classifyData from '@/common/classify.data.js';
	var _this;
	export default {
		computed: {
			appCateHeight() {
				// #ifdef APP-PLUS
				return this.cateH + 'px'
				// #endif

				// #ifndef APP-PLUS
				return 'auto'
				// #endif
			}
		},
		data() {
			return {
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				itemId: '', // 栏目右边scroll-view用于滚动的id
				tabbar: {}, //二级
				tabbarsun: [], //三级
				menuItemPos: [],
				arr: [],
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null, // 定时器,
				scrolllist: [], //分类列表
				cat_id_1: 0,
				cat_id_2: 0,
				page: 1,
				id: 0,
				bottom: 0,
				loginShow: false,
				loginDisabled: false,
				paddingRight: 10,
				statusbarH: 0,
				cateH: 0,
			}
		},
		onLoad() {
			_this = this
			// #ifdef APP-PLUS
			let winInfo = uni.getWindowInfo();
			this.statusbarH = winInfo.statusBarHeight + 10
			this.cateH = winInfo.windowHeight - this.statusbarH - 44
			// #endif

			// #ifdef MP-WEIXIN
			let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.paddingRight = menuButtonInfo.width + 15
			// #endif
			this.getsortlist()
		},
		onPullDownRefresh() {
			this.tabbarsun = []
			this.cat_id_2 = 0
			this.getsortgoods(1)
		},
		methods: {
			async getPhoneNumber(e) {
				if (e.target.errMsg == "getPhoneNumber:ok") {
					_this.loginDisabled = true
					let res = {
						'encryptedData': e.target.encryptedData,
						'iv': e.target.iv,
						'sessionKey': uni.getStorageSync('sessionKey'),
						'tuid': uni.getStorageSync('tuid'),
						'reid': uni.getStorageSync('reid') || 0,
					}
					const data = await _this.$post('api/weixin_mobile', res)
					if (data.code == 200) {
						uni.$u.toast(data.msg)
						//存入用户信息
						_this.$u.vuex('user_id', data.data.user.user_id)
						//存入token
						_this.$u.vuex('user_token', data.data.user.user_token)
					} else {
						uni.$u.toast(data.msg)
					}
					setTimeout(() => {
						_this.loginShow = false
						_this.loginDisabled = false
					}, 2000)
				} else {
					uni.$u.toast('获取失败')
					_this.loginShow = false
				}
			},
			//加入购物车
			async addcart(id) {
				const params = {
					goods_id: id,
					item_id: 0,
					goods_num: 1
				}
				const data = await AddCart(params)
				if (data.code == 200) {
					this.$u.toast(data.msg)
				} else {
					this.$u.toast(data.msg)
				}
			},
			//获取分类数据
			async getsortlist() {
				const data = await _this.$post('api/GoodsCate')
				this.scrolllist = data.data.classes
				this.cat_id_1 = this.scrolllist[0]['id']
				this.getsortgoods(1)
			},
			//获取分类的商品数据
			async getsortgoods(type) {
				const params = {
					pageIndex: this.page,
					pageSize: 20,
					cat_id_1: this.cat_id_1,
					cat_id_2: this.cat_id_2
				}
				const data = await _this.$post('api/CateGoods', params)
				if (type == 1) {
					this.tabbar = data.data.cates
					if (this.tabbar.length > 0) {
						this.cat_id_2 = this.tabbar[0]['id']
					}
				}
				this.tabbarsun.push(...data.data.goods)
				setTimeout(() => {
					uni.stopPullDownRefresh()
				}, 500)
			},
			//获取该分类数据
			scrolllistto(index) {
				// this.bottom = 0
				// console.log(index);
				// this.tabbar = this.scrolllist[index].children
				this.page = 1
				this.cat_id_1 = index
				this.cat_id_2 = 0
				this.tabbarsun = []
				// console.log(this.tabbar);
				this.getsortgoods(1);
			},

			// 点击左边的栏目切换
			async swichMenu(id) {
				if (this.cat_id_2 == id) {
					return;
				}
				this.page = 1
				this.cat_id_2 = id
				this.tabbarsun = []
				this.getsortgoods(2);
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			// 观测元素相交状态
			async observer() {
				this.tabbar.map((val, index) => {
					let observer = uni.createIntersectionObserver(this);
					// 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
					// 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
					observer.relativeTo('.right-box', {
						top: 0
					}).observe('#item' + index, res => {
						if (res.intersectionRatio > 0) {
							let id = res.id.substring(4);
							this.leftMenuStatus(id);
						}
					})
				})
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 获取右边菜单每个item到顶部的距离
			getMenuItemTop() {
				new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery().in(this);
					selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if (!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 20);
							return;
						}
						rects.forEach((rect) => {
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
							// this.arr.push(rect.top - rects[0].top);
							this.arr.push(rect.top - rects[0].top);
							resolve();
						})
					}).exec()
				})
			},
			// 右边菜单滚动
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if (this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (this.timer) return;
				if (!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					// scrollHeight为右边菜单垂直中点位置
					let scrollHeight = e.detail.scrollTop + this.menuHeight / 5;
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						// 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							return;
						}
					}
				}, 10)
			},
			//路由跳转
			jump(url, id) {
				this.$u.route({
					url,
					params: {
						id
					}
				})
			},
			//跳转至搜索
			tosearch() {
				this.$u.route('pages/sort/search')
			},
			//底部监听
			scrolltolower() {
				this.page++;
				this.getsortgoods(2);
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/goods.scss";

	.u-wrap {
		height: 100%;
		/* #ifdef H5 */
		height: calc(100% - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.status-bar {
		background: #fff;
	}

	.sort-search {
		height: 44px;
		box-sizing: border-box;
		padding: 0 10px 0 20rpx;
		background: #fff;
		border-bottom: $global-border;
		box-sizing: border-box;
	}

	.u-menu-wrap {
		height: calc(100% - 44px);
		overflow: hidden;
		display: flex;
		flex-direction: column;
		.left-view {
			width: 100%;
			display: flex;
			align-items: center;
			background: #fff;
			height: 80rpx;
			&-item {
				width: 20%;
				display: inline-block !important;
				height: 80rpx !important;
				line-height: 80rpx !important;
				text-align: center;
			}
			&-item::before {
				bottom: 0 !important;
				left: 50% !important;
				transform: translateX(-50%) !important;
				height: 8rpx !important;
				width: 30% !important;
				top:  auto !important;
				border-radius: 10rpx;
			}
		}
	}
	.cate {
		height: calc(100vh - 44px) !important;
		.right-view {
			width: 100%;
			background: #eee;
			box-sizing: border-box;
			padding: 0 2%;
			height: 100%;
			overflow-y: auto;
			padding-top: 30rpx;
			position: relative;
			.empty-container {
				padding: 30%;
			}
			.right-box {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				.goods-row-item {
					width: 48%;
					display: inline-block;
					box-sizing: border-box;
					background: #fff;
					margin-bottom: 20rpx;
					border-radius: 20rpx;
					image {
						width: 100%;
					}
					.right {
						margin-left: 0;
						.goods-name {
							font-size: 34rpx;
							padding-bottom: 10rpx;
						}
					}
				}
			}
		}
	}
</style>